#include "CalculatorWidget.h"
#include <QHBoxLayout>
#include <QDebug>

CalculatorWidget::CalculatorWidget(QWidget *parent) :
    QWidget(parent),
    firstOperand(BigDecimal()),
    currentNumber(BigDecimal()),
    currentOperation(""),
    isInputtingNumber(false),
    newNumberExpected(false)
{
    setupUi();
}

CalculatorWidget::~CalculatorWidget() {}

void CalculatorWidget::setupUi()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(5);

    // 显示区域
    displayLabel = new QLabel("0", this);
    displayLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    displayLabel->setFont(QFont("Arial", 24));
    displayLabel->setMinimumHeight(60);
    mainLayout->addWidget(displayLabel);

    // 按钮布局
    QGridLayout *buttonLayout = new QGridLayout();
    buttonLayout->setSpacing(3);

    // 数字按钮
    digitButtons.resize(10);
    for (int i = 0; i < 10; ++i) {
        digitButtons[i] = new QPushButton(QString::number(i), this);
        digitButtons[i]->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        connect(digitButtons[i], &QPushButton::clicked, this, &CalculatorWidget::onDigitPressed);
    }

    // 特殊按钮
    QPushButton *btnDecimal = new QPushButton(".", this);
    QPushButton *btnSign = new QPushButton("±", this);
    QPushButton *btnAdd = new QPushButton("+", this);
    QPushButton *btnSubtract = new QPushButton("-", this);
    QPushButton *btnEquals = new QPushButton("=", this);
    QPushButton *btnClear = new QPushButton("Cls", this);

    // 布局设置
    buttonLayout->addWidget(btnClear,    0, 0, 1, 2);
    buttonLayout->addWidget(btnSign,     0, 2);
    buttonLayout->addWidget(btnDecimal,  0, 3);

    buttonLayout->addWidget(digitButtons[7], 1, 0);
    buttonLayout->addWidget(digitButtons[8], 1, 1);
    buttonLayout->addWidget(digitButtons[9], 1, 2);
    buttonLayout->addWidget(btnAdd,      1, 3);

    buttonLayout->addWidget(digitButtons[4], 2, 0);
    buttonLayout->addWidget(digitButtons[5], 2, 1);
    buttonLayout->addWidget(digitButtons[6], 2, 2);
    buttonLayout->addWidget(btnSubtract, 2, 3);

    buttonLayout->addWidget(digitButtons[1], 3, 0);
    buttonLayout->addWidget(digitButtons[2], 3, 1);
    buttonLayout->addWidget(digitButtons[3], 3, 2);
    buttonLayout->addWidget(btnEquals,   3, 3, 2, 1);

    buttonLayout->addWidget(digitButtons[0], 4, 0, 1, 2);

    // 连接信号槽
    connect(btnDecimal, &QPushButton::clicked, this, &CalculatorWidget::onDecimalPressed);
    connect(btnSign, &QPushButton::clicked, this, &CalculatorWidget::onSignPressed);
    connect(btnAdd, &QPushButton::clicked, this, &CalculatorWidget::onOperatorPressed);
    connect(btnSubtract, &QPushButton::clicked, this, &CalculatorWidget::onOperatorPressed);
    connect(btnEquals, &QPushButton::clicked, this, &CalculatorWidget::onEqualsPressed);
    connect(btnClear, &QPushButton::clicked, this, &CalculatorWidget::onClearPressed);

    mainLayout->addLayout(buttonLayout);
    setLayout(mainLayout);
}

void CalculatorWidget::onDigitPressed()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    QString digit = button->text();
    QString numStr = QString::fromStdString(currentNumber.toString());

    if (newNumberExpected) {
        numStr = "0";
        newNumberExpected = false;
    }

    if (numStr == "0" && digit != ".") {
        numStr = digit;
    } else {
        // 处理小数点后追加数字
        if (numStr.contains('.')) {
            numStr += digit;
            currentNumber = BigDecimal(numStr.toStdString(),false);
            goto label1;
        } else {
            numStr += digit;
        }
    }

    currentNumber = BigDecimal(numStr.toStdString());
label1:   updateDisplay();
}

void CalculatorWidget::onDecimalPressed()
{
    QString numStr = QString::fromStdString(currentNumber.toString());

    // 处理小数逻辑
    if (!numStr.contains('.')) {
        if (numStr.isEmpty() || newNumberExpected) {
            numStr = "0.";
        } else {
            numStr += ".";
        }
        currentNumber = BigDecimal(numStr.toStdString());
        isInputtingNumber = true;
        newNumberExpected = false;
        updateDisplay();
    }
}


void CalculatorWidget::onSignPressed()
{
    QString numStr = QString::fromStdString(currentNumber.toString());

    // 切换符号逻辑
    if (!numStr.isEmpty() && numStr != "0") {
        if (numStr.startsWith('-')) {
            numStr.remove(0, 1);
        } else {
            numStr.prepend('-');
        }
    }

    currentNumber = BigDecimal(numStr.toStdString());
    updateDisplay();
}

void CalculatorWidget::onOperatorPressed()
{
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    if (!button) return;

    QString op = button->text();
    QString numStr = QString::fromStdString(currentNumber.toString());

    // 构建表达式显示
    if (currentExpression.isEmpty()) {
        currentExpression = numStr + " " + op + " ";
    } else {
        currentExpression += numStr + " " + op + " ";
    }

    // 显示完整表达式
    displayLabel->setText(currentExpression);

    // 保存操作数
    firstOperand = currentNumber;
    pendingOperator = op;
    newNumberExpected = true;
}

void CalculatorWidget::onEqualsPressed()
{
    if (pendingOperator.isEmpty()) return;

    QString numStr = QString::fromStdString(currentNumber.toString());
    currentExpression += numStr + " = ";

    // 执行计算
    performOperation();

    // 显示完整计算过程及结果
    displayLabel->setText(currentExpression + QString::fromStdString(currentNumber.toString()));
    currentExpression.clear();
}

void CalculatorWidget::onClearPressed()
{
    currentNumber = BigDecimal();
    firstOperand = BigDecimal();
    currentOperation.clear();
    isInputtingNumber = false;
    displayLabel->setText("0");
}

void CalculatorWidget::updateDisplay()
{
    QString displayStr = QString::fromStdString(currentNumber.toString());
    displayLabel->setText(displayStr);
}

void CalculatorWidget::performOperation() {
    if (pendingOperator == "+") {
        currentNumber = firstOperand + currentNumber;
    } else if (pendingOperator == "-") {
        currentNumber = firstOperand - currentNumber;
    }
    // 其他运算符处理
}
